import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Button, Card, Typography, Space, message } from 'antd';
import { ClearOutlined, CalendarOutlined } from '@ant-design/icons';
import moment, { type Moment } from 'moment';

const { Title, Text } = Typography;

// 定义时间段类型
interface TimeSlot {
  id: string;
  date: Moment;
  isSelected: boolean;
  isTemporary: boolean; // 用于滑动过程中的临时高亮
  hour: number;
  minute: number;
}

// 生成7天的时间段数据
const generateTimeSlots = (): TimeSlot[] => {
  const slots: TimeSlot[] = [];
  
  // 生成从今天开始的7天
  for (let day = 0; day < 7; day++) {
    // 每个小时有2个30分钟的时间段
    for (let hour = 0; hour < 24; hour++) {
      for (let minute of [0, 30]) {
        const date = moment().add(day, 'days').hour(hour).minute(minute).second(0).millisecond(0);
        slots.push({
          id: `${date.format('YYYYMMDDHHmm')}`,
          date,
          isSelected: false,
          isTemporary: false,
          hour,
          minute
        });
      }
    }
  }
  
  return slots;
};

const TimeRangeSelector: React.FC = () => {
  const [timeSlots, setTimeSlots] = useState<TimeSlot[]>([]);
  const [isSelecting, setIsSelecting] = useState<boolean>(false); // 是否处于选择模式（已点击开始点）
  const [startSlotId, setStartSlotId] = useState<string | null>(null);
  const [selectedRange, setSelectedRange] = useState<{start: Moment | null, end: Moment | null}>({
    start: null,
    end: null
  });
  
  const gridRef = useRef<HTMLDivElement>(null);
  
  // 初始化时间段数据
  useEffect(() => {
    setTimeSlots(generateTimeSlots());
  }, []);
  
  // 处理开始选择（第一次点击）
  const handleStartSelect = useCallback((slotId: string) => {
    // 如果已经在选择模式中，点击视为结束选择
    if (isSelecting) {
      handleEndSelect(slotId);
      return;
    }
    
    // 进入选择模式
    setIsSelecting(true);
    setStartSlotId(slotId);
    
    // 清除之前的选择和临时高亮
    const updatedSlots = timeSlots.map(slot => ({
      ...slot,
      isSelected: false,
      isTemporary: slot.id === slotId
    }));
    
    const selectedSlot = updatedSlots.find(slot => slot.id === slotId);
    setSelectedRange({
      start: selectedSlot?.date || null,
      end: null
    });
    
    setTimeSlots(updatedSlots);
    message.info(`开始选择: ${selectedSlot?.date.format('MM-DD HH:mm')}`);
  }, [isSelecting, timeSlots]);
  
  // 处理滑动预览
  const handleMouseMove = useCallback((slotId: string) => {
    if (!isSelecting || !startSlotId || startSlotId === slotId) return;
    
    // 找到起始和当前的索引
    const startIndex = timeSlots.findIndex(slot => slot.id === startSlotId);
    const currentIndex = timeSlots.findIndex(slot => slot.id === slotId);
    
    if (startIndex === -1 || currentIndex === -1) return;
    
    // 确定临时选择范围
    const start = Math.min(startIndex, currentIndex);
    const end = Math.max(startIndex, currentIndex);
    
    // 更新临时高亮状态
    const updatedSlots = timeSlots.map((slot, index) => ({
      ...slot,
      isTemporary: index >= start && index <= end
    }));
    
    setTimeSlots(updatedSlots);
  }, [isSelecting, startSlotId, timeSlots]);
  
  // 处理结束选择（第二次点击）
  const handleEndSelect = useCallback((slotId: string) => {
    if (!startSlotId) return;
    
    // 找到起始和结束的索引
    const startIndex = timeSlots.findIndex(slot => slot.id === startSlotId);
    const endIndex = timeSlots.findIndex(slot => slot.id === slotId);
    
    if (startIndex === -1 || endIndex === -1) return;
    
    // 确定最终选择范围
    const start = Math.min(startIndex, endIndex);
    const end = Math.max(startIndex, endIndex);
    
    // 更新选择状态，清除临时高亮
    const updatedSlots = timeSlots.map((slot, index) => ({
      ...slot,
      isSelected: index >= start && index <= end,
      isTemporary: false
    }));
    
    // 更新选择范围信息
    const startSlot = updatedSlots[start];
    const endSlot = updatedSlots[end];
    
    setTimeSlots(updatedSlots);
    setSelectedRange({
      start: startSlot.date,
      end: endSlot.date
    });
    
    // 退出选择模式
    setIsSelecting(false);
    setStartSlotId(null);
    
    message.success(`已选择: ${startSlot.date.format('MM-DD HH:mm')} 至 ${endSlot.date.format('MM-DD HH:mm')}`);
  }, [startSlotId, timeSlots]);
  
  // 清除选择
  const handleClearSelection = () => {
    const updatedSlots = timeSlots.map(slot => ({
      ...slot,
      isSelected: false,
      isTemporary: false
    }));
    
    setTimeSlots(updatedSlots);
    setSelectedRange({
      start: null,
      end: null
    });
    setIsSelecting(false);
    setStartSlotId(null);
    
    message.info('已清除选择');
  };
  
  // 获取所有日期（7天）
  const getUniqueDates = () => {
    const dates = new Map<string, Moment>();
    
    timeSlots.forEach(slot => {
      const dateStr = slot.date.format('YYYY-MM-DD');
      if (!dates.has(dateStr)) {
        dates.set(dateStr, slot.date);
      }
    });
    
    return Array.from(dates.values());
  };
  
  // 获取一天中的所有时间段（48个）
  const getTimeLabels = () => {
    const labels: string[] = [];
    
    for (let hour = 0; hour < 24; hour++) {
      for (let minute of [0, 30]) {
        labels.push(`${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`);
      }
    }
    
    return labels;
  };
  
  const uniqueDates = getUniqueDates();
  const timeLabels = getTimeLabels();
  
  return (
    <Card 
      title={
        <Space>
          <CalendarOutlined />
          <Title level={5} style={{ margin: 0 }}>7天时间段选择器</Title>
        </Space>
      }
      extra={
        <Button 
          icon={<ClearOutlined />} 
          onClick={handleClearSelection}
          disabled={!selectedRange.start || !selectedRange.end}
        >
          清除选择
        </Button>
      }
      style={{ margin: 20 }}
    >
      {selectedRange.start && selectedRange.end ? (
        <div style={{ marginBottom: 16, padding: 8, backgroundColor: '#f5f5f5', borderRadius: 4 }}>
          <Text strong>当前选择:</Text>
          <Text> {selectedRange.start.format('MM-DD HH:mm')} 至 {selectedRange.end.format('MM-DD HH:mm')}</Text>
          <Text> (共 {(selectedRange.end.diff(selectedRange.start, 'minutes') / 60).toFixed(1)} 小时)</Text>
        </div>
      ) : isSelecting && selectedRange.start ? (
        <div style={{ marginBottom: 16, padding: 8, backgroundColor: '#fffbe6', borderRadius: 4 }}>
          <Text strong>选择中:</Text>
          <Text> 从 {selectedRange.start.format('MM-DD HH:mm')} 开始，点击结束时间完成选择</Text>
        </div>
      ) : null}
      
      <div 
        ref={gridRef}
        style={{ 
          overflow: 'auto',
          maxHeight: 600,
          border: '1px solid #e8e8e8',
          borderRadius: 4
        }}
      >
        {/* 日期行 - 顶部 */}
        <div style={{ display: 'flex' }}>
          {/* 左上角标题单元格 - 已将"时间/日期"改为"日期/时间" */}
          <div style={{ 
            minWidth: 80,
            height: 40, 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center',
            fontWeight: 'bold',
            borderBottom: '1px solid #e8e8e8',
            borderRight: '1px solid #e8e8e8',
            backgroundColor: '#fafafa'
          }}>
            日期/时间
          </div>
          
          {/* 日期标题 */}
          {uniqueDates.map((date, dateIndex) => (
            <div key={dateIndex} style={{ 
              minWidth: 80,
              height: 40, 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center',
              fontWeight: 'bold',
              borderBottom: '1px solid #e8e8e8',
              borderRight: '1px solid #e8e8e8',
              backgroundColor: '#fafafa'
            }}>
              <div style={{ textAlign: 'center' }}>
                <div>{date.format('MM-DD')}</div>
                <div style={{ fontSize: 12 }}>{['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.day()]}</div>
              </div>
            </div>
          ))}
        </div>
        
        {/* 时间段行 - 下方 */}
        {timeLabels.map((timeLabel, timeIndex) => (
          <div key={timeIndex} style={{ display: 'flex' }}>
            {/* 时间标签列 */}
            <div style={{ 
              minWidth: 80,
              height: 30, 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center',
              borderBottom: '1px solid #e8e8e8',
              borderRight: '1px solid #e8e8e8',
              fontSize: 12,
              backgroundColor: timeIndex % 2 === 0 ? '#fff' : '#f9f9f9'
            }}>
              {timeLabel}
            </div>
            
            {/* 时间段方块 */}
            {uniqueDates.map((date, dateIndex) => {
              const slotId = `${date.format('YYYYMMDD')}${timeLabel.replace(':', '')}`;
              const slot = timeSlots.find(s => s.id === slotId);
              
              // 确定方块背景色
              let bgColor = (timeIndex % 2 === 0 ? '#fff' : '#f9f9f9');
              if (slot?.isSelected) {
                bgColor = '#1890ff'; // 已选择的方块
              } else if (slot?.isTemporary) {
                bgColor = '#40a9ff'; // 临时选择的方块（滑动过程中）
              }
              
              return (
                <div
                  key={`${dateIndex}-${timeIndex}`}
                  id={slotId}
                  style={{ 
                    minWidth: 80,
                    height: 30, 
                    borderBottom: '1px solid #e8e8e8',
                    borderRight: '1px solid #e8e8e8',
                    backgroundColor: bgColor,
                    cursor: 'pointer',
                    transition: 'background-color 0.2s'
                  }}
                  onClick={() => handleStartSelect(slotId)}
                  onMouseEnter={() => handleMouseMove(slotId)}
                />
              );
            })}
          </div>
        ))}
      </div>
      
      <div style={{ marginTop: 16, fontSize: 12, color: '#666' }}>
        <Text>提示: 点击第一个方块作为开始，滑动鼠标预览选择范围，点击第二个方块作为结束完成选择。</Text>
      </div>
    </Card>
  );
};

export default TimeRangeSelector;
